<!DOCTYPE html>
<html lang=zh>
<head>
    <meta charset="utf-8">
    
    <title>第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置 | 恒宇少年De成长之路</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <meta name="description" content="在这次SpringBoot升级后，之前的系统内使用实体传输受到了限制，如果使用SpringBoot默认的序列化方式不会出现信任package的问题，之所以出现这个问题是因为项目使用fastjson方式进行类的序列化已经反序列化，在之前SpringBoot 1.5.10版本的时候 RabbitMQ依赖内的DefaultClassMapper类在构造函数内配置*，表示信任项目内的所有package，在">
<meta name="keywords" content="SpringBoot">
<meta property="og:type" content="article">
<meta property="og:title" content="第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置">
<meta property="og:url" content="http://blog.yuqiyu.com/spring-boot-chapter-48/index.html">
<meta property="og:site_name" content="恒宇少年De成长之路">
<meta property="og:description" content="在这次SpringBoot升级后，之前的系统内使用实体传输受到了限制，如果使用SpringBoot默认的序列化方式不会出现信任package的问题，之所以出现这个问题是因为项目使用fastjson方式进行类的序列化已经反序列化，在之前SpringBoot 1.5.10版本的时候 RabbitMQ依赖内的DefaultClassMapper类在构造函数内配置*，表示信任项目内的所有package，在">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/4461954-d80b777ca38632ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-03-13T14:42:44.137Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置">
<meta name="twitter:description" content="在这次SpringBoot升级后，之前的系统内使用实体传输受到了限制，如果使用SpringBoot默认的序列化方式不会出现信任package的问题，之所以出现这个问题是因为项目使用fastjson方式进行类的序列化已经反序列化，在之前SpringBoot 1.5.10版本的时候 RabbitMQ依赖内的DefaultClassMapper类在构造函数内配置*，表示信任项目内的所有package，在">
<meta name="twitter:image" content="http://upload-images.jianshu.io/upload_images/4461954-d80b777ca38632ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
    

    
        <link rel="alternate" href="/" title="恒宇少年De成长之路" type="application/atom+xml" />
    

    

    <link rel="stylesheet" href="/libs/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="/libs/open-sans/styles.css">
    <link rel="stylesheet" href="/libs/source-code-pro/styles.css">

    <link rel="stylesheet" href="/css/style.css">

    <script src="/libs/jquery/2.1.3/jquery.min.js"></script>
    
    
        <link rel="stylesheet" href="/libs/lightgallery/css/lightgallery.min.css">
    
    
        <link rel="stylesheet" href="/libs/justified-gallery/justifiedGallery.min.css">
    
    
    
    


</head>

<body>
    <div id="container">
        <header id="header">
    <div id="header-main" class="header-inner">
        <div class="outer">
            <a href="/" id="logo">
                <i class="logo"></i>
                <span class="site-title">恒宇少年De成长之路</span>
            </a>
            <nav id="main-nav">
                
                    <a class="main-nav-link" href="/.">首页</a>
                
                    <a class="main-nav-link" href="/archives">时间轴</a>
                
                    <a class="main-nav-link" href="/categories">文章专题</a>
                
                    <a class="main-nav-link" href="/tags">标签云</a>
                
                    <a class="main-nav-link" href="/about">关于我</a>
                
            </nav>
            
                
                <nav id="sub-nav">
                    <div class="profile" id="profile-nav">
                        <a id="profile-anchor" href="javascript:;">
                            <img class="avatar" src="/css/images/avatar.png" />
                            <i class="fa fa-caret-down"></i>
                        </a>
                    </div>
                </nav>
            
            <div id="search-form-wrap">

    <form class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
        <!--button type="submit" class="search-form-submit"></button-->
    </form>
    <div class="ins-search">
    <div class="ins-search-mask"></div>
    <div class="ins-search-container">
        <div class="ins-input-wrapper">
            <input type="text" class="ins-search-input" placeholder="想要查找什么..." />
            <span class="ins-close ins-selectable"><i class="fa fa-times-circle"></i></span>
        </div>
        <div class="ins-section-wrapper">
            <div class="ins-section-container"></div>
        </div>
    </div>
</div>
<script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: '文章',
            PAGES: '页面',
            CATEGORIES: '分类',
            TAGS: '标签',
            UNTITLED: '(未命名)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>
<script src="/js/insight.js"></script>

</div>
        </div>
    </div>
    <div id="main-nav-mobile" class="header-sub header-inner">
        <table class="menu outer">
            <tr>
                
                    <td ><a  class="main-nav-link" href="/.">首页</a></td>
                
                    <td ><a  class="main-nav-link" href="/archives">时间轴</a></td>
                
                    <td ><a  class="main-nav-link" href="/categories">文章专题</a></td>
                
                    <td ><a  class="main-nav-link" href="/tags">标签云</a></td>
                
                    <td ><a  class="main-nav-link" href="/about">关于我</a></td>
                
                <td>
                    
    <div class="search-form">
        <input type="text" class="ins-search-input search-form-input" placeholder="搜索" />
    </div>

                </td>
            </tr>
        </table>
    </div>
</header>

        <div class="outer">
            
                

<aside id="profile">
    <div class="inner profile-inner">
        <div class="base-info profile-block">
            <img id="avatar" src="/css/images/avatar.png" />
            <h2 id="name">恒宇少年</h2>
            <h3 id="title">Java软件工程师 &amp; 程序猿</h3>
            <span id="location"><i class="fa fa-map-marker"></i>山东, 济南</span>
            <a id="follow" target="_blank" href="https://www.jianshu.com/u/092df3f77bca">关注我</a>
        </div>
        <div class="article-info profile-block">
            <div class="article-info-block">
                43
                <span>文章</span>
            </div>
            <div class="article-info-block">
                2
                <span>标签</span>
            </div>
        </div>
        
        <div class="profile-block social-links">
            <table>
                <tr>
                    
                    
                    <td>
                        <a href="http://github.com/ppoffice/hexo-theme-icarus" target="_blank" title="github" class=tooltip>
                            <i class="fa fa-github"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="twitter" class=tooltip>
                            <i class="fa fa-twitter"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="facebook" class=tooltip>
                            <i class="fa fa-facebook"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="dribbble" class=tooltip>
                            <i class="fa fa-dribbble"></i>
                        </a>
                    </td>
                    
                    <td>
                        <a href="/" target="_blank" title="rss" class=tooltip>
                            <i class="fa fa-rss"></i>
                        </a>
                    </td>
                    
                </tr>
            </table>
        </div>
        
    </div>
</aside>

            
            <section id="main"><article id="post-spring-boot-chapter-48" class="article article-type-post" itemscope itemprop="blogPost">
    <div class="article-inner">
        
        
            <header class="article-header">
                
    
        <h1 class="article-title" itemprop="name">
            第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置
        </h1>
    

                
                    <div class="article-meta">
                        
    <div class="article-date">
        <i class="fa fa-calendar"></i>
        <a href="/spring-boot-chapter-48/">
            <time datetime="2018-03-12T16:00:00.000Z" itemprop="datePublished">2018-03-13</time>
        </a>
    </div>


                        
    <div class="article-category">
    	<i class="fa fa-folder"></i>
        <a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a>
    </div>

                        
    <div class="article-tag">
        <i class="fa fa-tag"></i>
        <a class="tag-link" href="/tags/SpringBoot/">SpringBoot</a>
    </div>

                    </div>
                
            </header>
        
        
        <div class="article-entry" itemprop="articleBody">
        
            
            <p>在这次<code>SpringBoot</code>升级后，之前的系统内使用实体传输受到了限制，如果使用<code>SpringBoot</code>默认的序列化方式不会出现<code>信任package</code>的问题，之所以出现这个问题是因为项目使用<code>fastjson</code>方式进行类的<code>序列化</code>已经<code>反序列化</code>，在之前<code>SpringBoot 1.5.10</code>版本的时候 <code>RabbitMQ</code>依赖内的<code>DefaultClassMapper</code>类在构造函数内配置<code>*</code>，表示信任项目内的所有<code>package</code>，在<code>SpringBoot 2.0.0</code>版本时，<code>DefaultClassMapper</code>类源码构造函数进行了修改，不再信任全部<code>package</code>而是仅仅信任<code>java.util</code>、<code>java.lang</code>。<br><a id="more"></a></p>
<h1 id="本章目标"><a href="#本章目标" class="headerlink" title="本章目标"></a>本章目标</h1><p>基于<code>SpringBoot2.0</code>使用<code>RabbitMQ</code>自定义<code>MessageConverter</code>配置信任指定<code>package</code>或者全部<code>package</code>。</p>
<h1 id="SpringBoot-企业级核心技术学习专题"><a href="#SpringBoot-企业级核心技术学习专题" class="headerlink" title="SpringBoot 企业级核心技术学习专题"></a>SpringBoot 企业级核心技术学习专题</h1><table>
<thead>
<tr>
<th style="text-align:center">专题</th>
<th style="text-align:left">专题名称</th>
<th style="text-align:left">专题描述</th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:center">001</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/3f69deddbed3" target="_blank" rel="noopener">Spring Boot 核心技术</a></td>
<td style="text-align:left">讲解SpringBoot一些企业级层面的核心组件</td>
</tr>
<tr>
<td style="text-align:center">002</td>
<td style="text-align:left"><a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">Spring Boot 核心技术章节源码</a></td>
<td style="text-align:left">Spring Boot 核心技术简书每一篇文章码云对应源码</td>
</tr>
<tr>
<td style="text-align:center">003</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/1faac22666e7" target="_blank" rel="noopener">Spring Cloud 核心技术</a></td>
<td style="text-align:left">对Spring Cloud核心技术全面讲解</td>
</tr>
<tr>
<td style="text-align:center">004</td>
<td style="text-align:left"><a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">Spring Cloud 核心技术章节源码</a></td>
<td style="text-align:left">Spring Cloud 核心技术简书每一篇文章对应源码</td>
</tr>
<tr>
<td style="text-align:center">005</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/ab4789177827" target="_blank" rel="noopener">QueryDSL 核心技术</a></td>
<td style="text-align:left">全面讲解QueryDSL核心技术以及基于SpringBoot整合SpringDataJPA</td>
</tr>
<tr>
<td style="text-align:center">006</td>
<td style="text-align:left"><a href="http://www.jianshu.com/c/f1b269bb2fd6" target="_blank" rel="noopener">SpringDataJPA 核心技术</a></td>
<td style="text-align:left">全面讲解SpringDataJPA核心技术</td>
</tr>
</tbody>
</table>
<h1 id="构建项目"><a href="#构建项目" class="headerlink" title="构建项目"></a>构建项目</h1><p>创建项目添加对应依赖，<code>pom.xml</code>配置文件如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependencies&gt;</span><br><span class="line">        &lt;!--消息队列依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--web相关依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-web&lt;/artifactId&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--fastjson依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;com.alibaba&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;fastjson&lt;/artifactId&gt;</span><br><span class="line">            &lt;version&gt;1.2.44&lt;/version&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--lombok依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.projectlombok&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;lombok&lt;/artifactId&gt;</span><br><span class="line">            &lt;optional&gt;true&lt;/optional&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">        &lt;!--测试依赖--&gt;</span><br><span class="line">        &lt;dependency&gt;</span><br><span class="line">            &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</span><br><span class="line">            &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;</span><br><span class="line">            &lt;scope&gt;test&lt;/scope&gt;</span><br><span class="line">        &lt;/dependency&gt;</span><br><span class="line">    &lt;/dependencies&gt;</span><br></pre></td></tr></table></figure></p>
<h4 id="消息队列配置文件"><a href="#消息队列配置文件" class="headerlink" title="消息队列配置文件"></a>消息队列配置文件</h4><p>我们需要在<code>application.properties</code>配置文件内添加<code>RabbitMQ</code>相应的配置信息，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">spring.rabbitmq.host=localhost</span><br><span class="line">spring.rabbitmq.username=admin</span><br><span class="line">spring.rabbitmq.password=admin</span><br><span class="line">spring.rabbitmq.virtual-host=/hengyu</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>具体消息队列的连接配置信息需要根据实际情况填写。</p>
</blockquote>
<h4 id="队列常量配置"><a href="#队列常量配置" class="headerlink" title="队列常量配置"></a>队列常量配置</h4><p>我们之前的文章都是采用的<code>Enum</code>方式来配置队列相关的<code>Exchange</code>、<code>Name</code>、 <code>RouteKey</code>等相关的信息，使用枚举有个弊端，无法在注解内作为属性的值使用，所以我们之前的<code>Consumer</code>类配置监听的队列时都是字符串的形式，这样后期修改时还要修改多个地方（当然队列信息很少变动），我们本章使用<code>Constants</code>常量的形式进行配置，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 队列常量配置</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with IDEA.</span><br><span class="line"> * Date：2018/3/7</span><br><span class="line"> * Time：下午10:10</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">public interface QueueConstants &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 消息交换</span><br><span class="line">     */</span><br><span class="line">    String MESSAGE_EXCHANGE = &quot;message.direct.exchange&quot;;</span><br><span class="line">    /**</span><br><span class="line">     * 消息队列名称</span><br><span class="line">     */</span><br><span class="line">    String MESSAGE_QUEUE_NAME = &quot;message.queue&quot;;</span><br><span class="line">    /**</span><br><span class="line">     * 消息路由键</span><br><span class="line">     */</span><br><span class="line">    String MESSAGE_ROUTE_KEY = &quot;message.send&quot;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="示例消息队列JavaConfig配置"><a href="#示例消息队列JavaConfig配置" class="headerlink" title="示例消息队列JavaConfig配置"></a>示例消息队列JavaConfig配置</h4><p>本章是为了设置信任<code>package</code>，所以这里使用消息中心队列来模拟，配置代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息队列配置类</span><br><span class="line"> *</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with IDEA.</span><br><span class="line"> * Date：2018/3/7</span><br><span class="line"> * Time：下午10:07</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">@Configuration</span><br><span class="line">public class MessageRabbitMqConfiguration &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 交换配置</span><br><span class="line">     *</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public DirectExchange messageDirectExchange() &#123;</span><br><span class="line">        return (DirectExchange) ExchangeBuilder.directExchange(QueueConstants.MESSAGE_EXCHANGE)</span><br><span class="line">                .durable(true)</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 消息队列声明</span><br><span class="line">     *</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public Queue messageQueue() &#123;</span><br><span class="line">        return QueueBuilder.durable(QueueConstants.MESSAGE_QUEUE_NAME)</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 消息绑定</span><br><span class="line">     *</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public Binding messageBinding() &#123;</span><br><span class="line">        return BindingBuilder.bind(messageQueue())</span><br><span class="line">                .to(messageDirectExchange())</span><br><span class="line">                .with(QueueConstants.MESSAGE_ROUTE_KEY);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>上面配置类内添加<code>Exchange</code>、<code>Queue</code>、<code>Binding</code>等配置，将<code>messageQueue</code>使用<code>message.send</code>路由键与<code>messageDirectExchange</code>交换配置进行绑定。</p>
<p>我们在之前说了只有传递实体类时才会出现信任<code>package</code>问题，下面我们需要创建一个简单的消息传输实体，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息实体</span><br><span class="line"> *</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with IDEA.</span><br><span class="line"> * Date：2018/3/11</span><br><span class="line"> * Time：下午5:18</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">@Data</span><br><span class="line">public class MessageEntity implements Serializable &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 消息内容</span><br><span class="line">     */</span><br><span class="line">    private String content;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>该实体类仅添加了一个<code>content</code>字段，这样足够模拟我们的场景了，到这里我们的配置已经处理完，下面就是我们的队列的<code>Provider</code>以及<code>Consumer</code>的相关实体类编写。</p>
<h4 id="消息提供者"><a href="#消息提供者" class="headerlink" title="消息提供者"></a>消息提供者</h4><p>为队列<code>message.queue</code>添加<code>Provider</code>的代码实现，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息队列 - 消息提供者</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with IDEA.</span><br><span class="line"> * Date：2018/3/11</span><br><span class="line"> * Time：下午6:16</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">@Component</span><br><span class="line">public class MessageProvider &#123;</span><br><span class="line">    /**</span><br><span class="line">     * logger instance</span><br><span class="line">     */</span><br><span class="line">    static Logger logger = LoggerFactory.getLogger(MessageProvider.class);</span><br><span class="line">    /**</span><br><span class="line">     * 消息队列模板</span><br><span class="line">     */</span><br><span class="line">    @Autowired</span><br><span class="line">    private AmqpTemplate amqpTemplate;</span><br><span class="line"></span><br><span class="line">    public void sendMessage(Object object) &#123;</span><br><span class="line">        logger.info(&quot;写入消息队列内容：&#123;&#125;&quot;, JSON.toJSONString(object));</span><br><span class="line">        amqpTemplate.convertAndSend(QueueConstants.MESSAGE_EXCHANGE, QueueConstants.MESSAGE_ROUTE_KEY, object);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="消息消费者"><a href="#消息消费者" class="headerlink" title="消息消费者"></a>消息消费者</h4><p>当然我们有了<code>Provider</code>必然要有对应的<code>Consumer</code>，消费者代码实现如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息队列 - 消息消费者</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with IDEA.</span><br><span class="line"> * Date：2018/3/11</span><br><span class="line"> * Time：下午5:32</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">@Component</span><br><span class="line">@RabbitListener(queues = QueueConstants.MESSAGE_QUEUE_NAME)</span><br><span class="line">public class MessageConsumer &#123;</span><br><span class="line">    /**</span><br><span class="line">     * logger instance</span><br><span class="line">     */</span><br><span class="line">    static Logger logger = LoggerFactory.getLogger(MessageConsumer.class);</span><br><span class="line"></span><br><span class="line">    @RabbitHandler</span><br><span class="line">    public void handler(@Payload MessageEntity messageEntity) &#123;</span><br><span class="line">        logger.info(&quot;消费内容：&#123;&#125;&quot;, JSON.toJSONString(messageEntity));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="创建测试控制器"><a href="#创建测试控制器" class="headerlink" title="创建测试控制器"></a>创建测试控制器</h4><p>我们采用控制器发送<code>Get</code>请求的方式进行发送消息，创建名为<code>TestController</code>的控制器，并添加测试方法，如下代码所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 测试控制器</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with IDEA.</span><br><span class="line"> * Date：2018/3/11</span><br><span class="line"> * Time：下午5:43</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">@RestController</span><br><span class="line">public class TestController &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 消息队列 - 消息提供者 注入</span><br><span class="line">     */</span><br><span class="line">    @Autowired</span><br><span class="line">    private MessageProvider messageProvider;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 测试发送消息队列方法</span><br><span class="line">     *</span><br><span class="line">     * @param messageEntity 发送消息实体内容</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @RequestMapping(value = &quot;/index&quot;)</span><br><span class="line">    public String index(MessageEntity messageEntity) &#123;</span><br><span class="line">        // 将实体实例写入消息队列</span><br><span class="line">        messageProvider.sendMessage(messageEntity);</span><br><span class="line">        return &quot;Success&quot;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="测试RabbitMQ默认实体传输"><a href="#测试RabbitMQ默认实体传输" class="headerlink" title="测试RabbitMQ默认实体传输"></a>测试RabbitMQ默认实体传输</h4><blockquote>
<p>下面我们启动项目，首先先来测试<code>RabbitMQ</code>默认的实体类方式，当然这种默认的方式不会产生信任<code>package</code>的情况。</p>
</blockquote>
<p>我们为了证实这一点，来访问(<a href="http://localhost:8080/index?content=admin)[http://localhost:8080/index?content=admin]，我们传递`content`的值为`admin`，访问效果控制台输出内容如下：" target="_blank" rel="noopener">http://localhost:8080/index?content=admin)[http://localhost:8080/index?content=admin]，我们传递`content`的值为`admin`，访问效果控制台输出内容如下：</a><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">2018-03-13 21:59:08.844  INFO 16047 --- [nio-8080-exec-1] c.h.chapter48.provider.MessageProvider   : 写入消息队列内容：&#123;&quot;content&quot;:&quot;admin&quot;&#125;</span><br><span class="line">2018-03-13 21:59:08.898  INFO 16047 --- [cTaskExecutor-1] c.h.chapter48.consumer.MessageConsumer   : 消费内容：&#123;&quot;content&quot;:&quot;admin&quot;&#125;</span><br></pre></td></tr></table></figure></p>
<p>可以看到控制台的输出内容，直接完成了消息的消费，是没有任何问题的，下面我们对<code>RabbitMQ</code>添加自定义<code>MessageConverter</code>的配置，使用<code>fastjson</code>替代默认转换方式。</p>
<h4 id="MessageConverter"><a href="#MessageConverter" class="headerlink" title="MessageConverter"></a>MessageConverter</h4><p>我们先来创建一个转换的实现类，只需要继承抽象类<code>AbstractMessageConverter</code>并实现内部的<code>createMessage</code>、<code>fromMessage</code>两个方法就可以完成实体类的<code>序列化</code>与<code>反序列化</code>的转换，代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 自定义消息转换器</span><br><span class="line"> * 采用FastJson完成消息转换</span><br><span class="line"> *</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with Eclipse.</span><br><span class="line"> * Date：2017/10/26</span><br><span class="line"> * Time：19:28</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">public class RabbitMqFastJsonConverter</span><br><span class="line">        extends AbstractMessageConverter &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 日志对象实例</span><br><span class="line">     */</span><br><span class="line">    private Logger logger = LoggerFactory.getLogger(RabbitMqFastJsonConverter.class);</span><br><span class="line">    /**</span><br><span class="line">     * 消息类型映射对象</span><br><span class="line">     */</span><br><span class="line">    private static ClassMapper classMapper = new DefaultClassMapper();</span><br><span class="line">    /**</span><br><span class="line">     * 默认字符集</span><br><span class="line">     */</span><br><span class="line">    private static String DEFAULT_CHART_SET = &quot;UTF-8&quot;;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 创建消息</span><br><span class="line">     *</span><br><span class="line">     * @param o                 消息对象</span><br><span class="line">     * @param messageProperties 消息属性</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    protected Message createMessage(Object o, MessageProperties messageProperties) &#123;</span><br><span class="line">        byte[] bytes = null;</span><br><span class="line">        try &#123;</span><br><span class="line">            String jsonString = JSON.toJSONString(o);</span><br><span class="line">            bytes = jsonString.getBytes(DEFAULT_CHART_SET);</span><br><span class="line">        &#125; catch (IOException e) &#123;</span><br><span class="line">            throw new MessageConversionException(</span><br><span class="line">                    &quot;Failed to convert Message content&quot;, e);</span><br><span class="line">        &#125;</span><br><span class="line">        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);</span><br><span class="line">        messageProperties.setContentEncoding(DEFAULT_CHART_SET);</span><br><span class="line">        if (bytes != null) &#123;</span><br><span class="line">            messageProperties.setContentLength(bytes.length);</span><br><span class="line">        &#125;</span><br><span class="line">        classMapper.fromClass(o.getClass(), messageProperties);</span><br><span class="line">        return new Message(bytes, messageProperties);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 转换消息为对象</span><br><span class="line">     *</span><br><span class="line">     * @param message 消息对象</span><br><span class="line">     * @return</span><br><span class="line">     * @throws MessageConversionException</span><br><span class="line">     */</span><br><span class="line">    @Override</span><br><span class="line">    public Object fromMessage(Message message) throws MessageConversionException &#123;</span><br><span class="line">        Object content = null;</span><br><span class="line">        MessageProperties properties = message.getMessageProperties();</span><br><span class="line">        if (properties != null) &#123;</span><br><span class="line">            String contentType = properties.getContentType();</span><br><span class="line">            if (contentType != null &amp;&amp; contentType.contains(&quot;json&quot;)) &#123;</span><br><span class="line">                String encoding = properties.getContentEncoding();</span><br><span class="line">                if (encoding == null) &#123;</span><br><span class="line">                    encoding = DEFAULT_CHART_SET;</span><br><span class="line">                &#125;</span><br><span class="line">                try &#123;</span><br><span class="line">                    Class&lt;?&gt; targetClass = classMapper.toClass(</span><br><span class="line">                            message.getMessageProperties());</span><br><span class="line"></span><br><span class="line">                    content = convertBytesToObject(message.getBody(),</span><br><span class="line">                            encoding, targetClass);</span><br><span class="line">                &#125; catch (IOException e) &#123;</span><br><span class="line">                    throw new MessageConversionException(</span><br><span class="line">                            &quot;Failed to convert Message content&quot;, e);</span><br><span class="line">                &#125;</span><br><span class="line">            &#125; else &#123;</span><br><span class="line">                logger.warn(&quot;Could not convert incoming message with content-type [&quot;</span><br><span class="line">                        + contentType + &quot;]&quot;);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        if (content == null) &#123;</span><br><span class="line">            content = message.getBody();</span><br><span class="line">        &#125;</span><br><span class="line">        return content;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 将字节数组转换成实例对象</span><br><span class="line">     *</span><br><span class="line">     * @param body     Message对象主体字节数组</span><br><span class="line">     * @param encoding 字符集</span><br><span class="line">     * @param clazz    类型</span><br><span class="line">     * @return</span><br><span class="line">     * @throws UnsupportedEncodingException</span><br><span class="line">     */</span><br><span class="line">    private Object convertBytesToObject(byte[] body, String encoding,</span><br><span class="line">                                        Class&lt;?&gt; clazz) throws UnsupportedEncodingException &#123;</span><br><span class="line">        String contentAsString = new String(body, encoding);</span><br><span class="line">        return JSON.parseObject(contentAsString, clazz);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在该转换类内我们使用了<code>DefaultClassMapper</code>来作为类的映射，我们可以先来看下该类相关信任<code>package</code>的源码，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">......</span><br><span class="line">public class DefaultClassMapper implements ClassMapper, InitializingBean &#123;</span><br><span class="line">    public static final String DEFAULT_CLASSID_FIELD_NAME = &quot;__TypeId__&quot;;</span><br><span class="line">    private static final String DEFAULT_HASHTABLE_TYPE_ID = &quot;Hashtable&quot;;</span><br><span class="line">    // 默认信任的package列表</span><br><span class="line">    private static final List&lt;String&gt; TRUSTED_PACKAGES = Arrays.asList(&quot;java.util&quot;, &quot;java.lang&quot;);</span><br><span class="line">    private final Set&lt;String&gt; trustedPackages;</span><br><span class="line">    private volatile Map&lt;String, Class&lt;?&gt;&gt; idClassMapping;</span><br><span class="line">    private volatile Map&lt;Class&lt;?&gt;, String&gt; classIdMapping;</span><br><span class="line">    private volatile Class&lt;?&gt; defaultMapClass;</span><br><span class="line">    private volatile Class&lt;?&gt; defaultType;</span><br><span class="line"></span><br><span class="line">    public DefaultClassMapper() &#123;</span><br><span class="line">        // 构造函数初始化信任的package为默认的pakcage列表</span><br><span class="line">        // 仅支持java.util、java.lang两个package</span><br><span class="line">        this.trustedPackages = new LinkedHashSet(TRUSTED_PACKAGES);</span><br><span class="line">        this.idClassMapping = new HashMap();</span><br><span class="line">        this.classIdMapping = new HashMap();</span><br><span class="line">        this.defaultMapClass = LinkedHashMap.class;</span><br><span class="line">        this.defaultType = LinkedHashMap.class;</span><br><span class="line">    &#125;</span><br><span class="line">......</span><br></pre></td></tr></table></figure></p>
<h4 id="RabbitMqConfiguration"><a href="#RabbitMqConfiguration" class="headerlink" title="RabbitMqConfiguration"></a>RabbitMqConfiguration</h4><p>下面我们需要将该转换设置到<code>RabbitTemplate</code>、<code>SimpleRabbitListenerContainerFactory</code>内，让<code>RabbitMQ</code>支持自定义的消息转换，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * rabbitmq 相关配置</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with IDEA.</span><br><span class="line"> * Date：2018/3/11</span><br><span class="line"> * Time：下午5:42</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">@Configuration</span><br><span class="line">public class RabbitMqConfiguration &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 配置消息队列模版</span><br><span class="line">     * 并且设置MessageConverter为自定义FastJson转换器</span><br><span class="line">     * @param connectionFactory</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) &#123;</span><br><span class="line">        RabbitTemplate template = new RabbitTemplate(connectionFactory);</span><br><span class="line">        template.setMessageConverter(new RabbitMqFastJsonConverter());</span><br><span class="line">        return template;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    /**</span><br><span class="line">     * 自定义队列容器工厂</span><br><span class="line">     * 并且设置MessageConverter为自定义FastJson转换器</span><br><span class="line">     * @param connectionFactory</span><br><span class="line">     * @return</span><br><span class="line">     */</span><br><span class="line">    @Bean</span><br><span class="line">    public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) &#123;</span><br><span class="line">        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();</span><br><span class="line">        factory.setConnectionFactory(connectionFactory);</span><br><span class="line">        factory.setMessageConverter(new RabbitMqFastJsonConverter());</span><br><span class="line">        factory.setDefaultRequeueRejected(false);</span><br><span class="line">        return factory;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h4 id="重启测试"><a href="#重启测试" class="headerlink" title="重启测试"></a>重启测试</h4><p>上面的代码配置我们已经把<code>MessageConverter</code>改成了<code>fastjson</code>，重启项目，再次访问<a href="http://localhost:8080/index?content=admin" target="_blank" rel="noopener">http://localhost:8080/index?content=admin</a>路径，看下控制台输出日志内容如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">Caused by: java.lang.IllegalArgumentException: The class &apos;com.hengyu.chapter48.entity.MessageEntity&apos; is not in the trusted packages: [java.util, java.lang]. If you believe this class is safe to deserialize, please provide its name. If the serialization is only done by a trusted source, you can also enable trust all (*).</span><br><span class="line">	at org.springframework.amqp.support.converter.DefaultClassMapper.toClass(DefaultClassMapper.java:211) ~[spring-amqp-2.0.2.RELEASE.jar:2.0.2.RELEASE]</span><br><span class="line">	at org.springframework.amqp.support.converter.DefaultClassMapper.toClass(DefaultClassMapper.java:199) ~[spring-amqp-2.0.2.RELEASE.jar:2.0.2.RELEASE]</span><br><span class="line">	at com.hengyu.chapter48.RabbitMqFastJsonConverter.fromMessage(RabbitMqFastJsonConverter.java:88) ~[classes/:na]</span><br><span class="line">	at org.springframework.amqp.rabbit.listener.adapter.AbstractAdaptableMessageListener.extractMessage(AbstractAdaptableMessageListener.java:246) ~[spring-rabbit-2.0.2.RELEASE.jar:2.0.2.RELEASE]</span><br><span class="line">	at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter$MessagingMessageConverterAdapter.extractPayload(MessagingMessageListenerAdapter.java:266) ~[spring-rabbit-2.0.2.RELEASE.jar:2.0.2.RELEASE]</span><br><span class="line">	at org.springframework.amqp.support.converter.MessagingMessageConverter.fromMessage(MessagingMessageConverter.java:118) ~[spring-amqp-2.0.2.RELEASE.jar:2.0.2.RELEASE]</span><br><span class="line">	at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.toMessagingMessage(MessagingMessageListenerAdapter.java:168) ~[spring-rabbit-2.0.2.RELEASE.jar:2.0.2.RELEASE]</span><br><span class="line">	at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:115) ~[spring-rabbit-2.0.2.RELEASE.jar:2.0.2.RELEASE]</span><br><span class="line">	at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:1414) ~[spring-rabbit-2.0.2.RELEASE.jar:2.0.2.RELEASE]</span><br><span class="line">	... 8 common frames omitted</span><br></pre></td></tr></table></figure></p>
<p>可以看到控制台已经输出了不信任<code>com.hengyu.chapter48.entity.MessageEntity</code>实体的错误信息，也表明了仅信任<code>java.util</code>、<code>java.lang</code>两个<code>package</code>，下面我们就需要继承<code>DefaultClassMapper</code>来重写构造函数完成信任指定的<code>package</code>。</p>
<h4 id="重写DefaultClassMapper构造函数"><a href="#重写DefaultClassMapper构造函数" class="headerlink" title="重写DefaultClassMapper构造函数"></a>重写DefaultClassMapper构造函数</h4><p>创建一个名为<code>RabbitMqFastJsonClassMapper</code>的类并且继承<code>DefaultClassMapper</code>，如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * fastjson 转换映射</span><br><span class="line"> *</span><br><span class="line"> * @author：于起宇 &lt;br/&gt;</span><br><span class="line"> * ===============================</span><br><span class="line"> * Created with IDEA.</span><br><span class="line"> * Date：2018/3/13</span><br><span class="line"> * Time：下午10:17</span><br><span class="line"> * 简书：http://www.jianshu.com/u/092df3f77bca</span><br><span class="line"> * ================================</span><br><span class="line"> */</span><br><span class="line">public class RabbitMqFastJsonClassMapper extends DefaultClassMapper &#123;</span><br><span class="line">    /**</span><br><span class="line">     * 构造函数初始化信任所有pakcage</span><br><span class="line">     */</span><br><span class="line">    public RabbitMqFastJsonClassMapper() &#123;</span><br><span class="line">        super();</span><br><span class="line">        setTrustedPackages(&quot;*&quot;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在上面构造函数内我们设置了信任全部的<code>package</code>，添加了<code>RabbitMqFastJsonClassMapper</code>类后，需要让<code>MessageConverter</code>使用该类作为映射，修改<code>RabbitMqFastJsonConverter</code>部分代码如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">/**</span><br><span class="line"> * 消息类型映射对象</span><br><span class="line"> */</span><br><span class="line">private static ClassMapper classMapper = new DefaultClassMapper();</span><br><span class="line">&gt;&gt;&gt; 修改为 &gt;&gt;&gt;</span><br><span class="line">/**</span><br><span class="line">* 消息类型映射对象</span><br><span class="line">*/</span><br><span class="line">private static ClassMapper classMapper = new RabbitMqFastJsonClassMapper();</span><br></pre></td></tr></table></figure></p>
<h4 id="再次重启测试"><a href="#再次重启测试" class="headerlink" title="再次重启测试"></a>再次重启测试</h4><p>我们再次重启项目后，仍然访问<a href="http://localhost:8080/index?content=admin" target="_blank" rel="noopener">http://localhost:8080/index?content=admin</a>路径，查看控制台日志如下所示：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">2018-03-13 22:23:35.414  INFO 16121 --- [nio-8080-exec-1] c.h.chapter48.provider.MessageProvider   : 写入消息队列内容：&#123;&quot;content&quot;:&quot;admin&quot;&#125;</span><br><span class="line">2018-03-13 22:23:35.493  INFO 16121 --- [cTaskExecutor-1] c.h.chapter48.consumer.MessageConsumer   : 消费内容：&#123;&quot;content&quot;:&quot;admin&quot;&#125;</span><br></pre></td></tr></table></figure></p>
<p>根据日志输出已经证明可以正常的完成消息的消费。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>如果使用<code>RabbitMQ</code>默认的转换方式，并不会涉及到本章遇到的信任<code>package</code>问题，如果想自定义消息转换并且使用<code>DefaultClassMapper</code>作为映射，肯定会出现信任<code>package</code>的问题，所以如果需要自定义转换的小伙伴，记住要设置<code>trustedPackages</code>。</p>
<p>本章源码已经上传到码云：<br>SpringBoot配套源码地址：<a href="https://gitee.com/hengboy/spring-boot-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-boot-chapter</a><br>SpringCloud配套源码地址：<a href="https://gitee.com/hengboy/spring-cloud-chapter" target="_blank" rel="noopener">https://gitee.com/hengboy/spring-cloud-chapter</a><br>SpringBoot相关系列文章请访问：<a href="http://www.jianshu.com/p/9a08417e4e84" target="_blank" rel="noopener">目录：SpringBoot学习目录</a><br>QueryDSL相关系列文章请访问：<a href="http://www.jianshu.com/p/99a5ec5c3bd5" target="_blank" rel="noopener">QueryDSL通用查询框架学习目录</a><br>SpringDataJPA相关系列文章请访问：<a href="http://www.jianshu.com/p/615ed9c1fe84" target="_blank" rel="noopener">目录：SpringDataJPA学习目录</a>，感谢阅读！<br>欢迎加入QQ技术交流群，共同进步。<br><img src="http://upload-images.jianshu.io/upload_images/4461954-d80b777ca38632ba.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="QQ技术交流群"></p>

        
        </div>
        <footer class="article-footer">
            <div class="share-container">


    <div class="bdsharebuttonbox">
    <a href="#" class="bds_more" data-cmd="more">分享到：</a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间">QQ空间</a>
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博">新浪微博</a>
    <a href="#" class="bds_tqq" data-cmd="tqq" title="分享到腾讯微博">腾讯微博</a>
    <a href="#" class="bds_renren" data-cmd="renren" title="分享到人人网">人人网</a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信">微信</a>
</div>
<script>
window._bd_share_config={"common":{"bdSnsKey":{},"bdText":"","bdMini":"2","bdMiniList":false,"bdPic":"","bdStyle":"0","bdSize":"16"},"share":{"bdSize":16}};with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new Date()/36e5)];
</script>
<style>
    .bdshare_popup_box {
        border-radius: 4px;
        border: #e1e1e1 solid 1px;
    }
    .bdshare-button-style0-16 a,
    .bdshare-button-style0-16 .bds_more {
        padding-left: 20px;
        margin: 6px 10px 6px 0;
    }
    .bdshare_dialog_list a,
    .bdshare_popup_list a,
    .bdshare_popup_bottom a {
        font-family: 'Microsoft Yahei';
    }
    .bdshare_popup_top {
        display: none;
    }
    .bdshare_popup_bottom {
        height: auto;
        padding: 5px;
    }
</style>


</div>

            
    

        </footer>
    </div>
    
        
<nav id="article-nav">
    
        <a href="/spring-boot-chapter-49/" id="article-nav-newer" class="article-nav-link-wrap">
            <strong class="article-nav-caption">上一篇</strong>
            <div class="article-nav-title">
                
                    第四十九章：SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗？
                
            </div>
        </a>
    
    
        <a href="/spring-boot-chapter-47/" id="article-nav-older" class="article-nav-link-wrap">
            <strong class="article-nav-caption">下一篇</strong>
            <div class="article-nav-title">第四十七章：SpringBoot2.0新特性 - Quartz自动化配置集成</div>
        </a>
    
</nav>


    
</article>


    
    

</section>
            
			
				
<aside id="sidebar">
   
        
    <div class="widget-wrap">
        <h3 class="widget-title">最新文章</h3>
        <div class="widget">
            <ul id="recent-post" class="no-thumbnail">
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-52/" class="title">第五十二章：基于SpringBoot2使用Rest访问MongoDB数据</a></p>
                            <p class="item-date"><time datetime="2018-04-21T16:00:00.000Z" itemprop="datePublished">2018-04-22</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-51/" class="title">第五十一章：基于SpringBoot2 &amp; MongoDB完成自动化集成</a></p>
                            <p class="item-date"><time datetime="2018-04-15T16:00:00.000Z" itemprop="datePublished">2018-04-16</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-50/" class="title">第五十章：SpringBoot2.0新特性 - 岂止至今最简单redis缓存集成</a></p>
                            <p class="item-date"><time datetime="2018-04-14T16:00:00.000Z" itemprop="datePublished">2018-04-15</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-49/" class="title">第四十九章：SpringBoot2.0新特性 - 你get到WebMvcConfigurer两种配置方式了吗？</a></p>
                            <p class="item-date"><time datetime="2018-03-16T16:00:00.000Z" itemprop="datePublished">2018-03-17</time></p>
                        </div>
                    </li>
                
                    <li>
                        
                        <div class="item-inner">
                            <p class="item-category"><a class="article-category-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a></p>
                            <p class="item-title"><a href="/spring-boot-chapter-48/" class="title">第四十八章：SpringBoot2.0新特性 - RabbitMQ信任package设置</a></p>
                            <p class="item-date"><time datetime="2018-03-12T16:00:00.000Z" itemprop="datePublished">2018-03-13</time></p>
                        </div>
                    </li>
                
            </ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">分类</h3>
        <div class="widget">
            <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/QueryDSL-核心技术/">QueryDSL 核心技术</a><span class="category-list-count">7</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/SpringBoot-核心技术/">SpringBoot 核心技术</a><span class="category-list-count">36</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">归档</h3>
        <div class="widget">
            <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/04/">四月 2018</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/03/">三月 2018</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2018/01/">一月 2018</a><span class="archive-list-count">1</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/12/">十二月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/11/">十一月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/10/">十月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/09/">九月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/08/">八月 2017</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/07/">七月 2017</a><span class="archive-list-count">9</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/06/">六月 2017</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/05/">五月 2017</a><span class="archive-list-count">3</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2017/04/">四月 2017</a><span class="archive-list-count">5</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签</h3>
        <div class="widget">
            <ul class="tag-list"><li class="tag-list-item"><a class="tag-list-link" href="/tags/QueryDSL/">QueryDSL</a><span class="tag-list-count">7</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/SpringBoot/">SpringBoot</a><span class="tag-list-count">43</span></li></ul>
        </div>
    </div>

    
        
    <div class="widget-wrap">
        <h3 class="widget-title">标签云</h3>
        <div class="widget tagcloud">
            <a href="/tags/QueryDSL/" style="font-size: 10px;">QueryDSL</a> <a href="/tags/SpringBoot/" style="font-size: 20px;">SpringBoot</a>
        </div>
    </div>

    
        
    <div class="widget-wrap widget-list">
        <h3 class="widget-title">链接</h3>
        <div class="widget">
            <ul>
                
                    <li>
     				<a href="http://hexo.io" target="_blank">Hexo</a>
					</li>
                
            </ul>
        </div>
    </div>


    
    <div id="toTop" class="fa fa-angle-up"></div>
</aside>

				
        </div>
        <!--引入不蒜子-->
<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<footer id="footer">
    <div class="outer">
        <div id="footer-info" class="inner">
            <span  id="busuanzi_container_site_pv">本站总访问量<span id="busuanzi_value_site_pv"></span>次</span>
            &copy; 2017 - 2018 恒宇少年 - 版权所有<br>
        </div>
    </div>
</footer>

        


    
        <script src="/libs/lightgallery/js/lightgallery.min.js"></script>
        <script src="/libs/lightgallery/js/lg-thumbnail.min.js"></script>
        <script src="/libs/lightgallery/js/lg-pager.min.js"></script>
        <script src="/libs/lightgallery/js/lg-autoplay.min.js"></script>
        <script src="/libs/lightgallery/js/lg-fullscreen.min.js"></script>
        <script src="/libs/lightgallery/js/lg-zoom.min.js"></script>
        <script src="/libs/lightgallery/js/lg-hash.min.js"></script>
        <script src="/libs/lightgallery/js/lg-share.min.js"></script>
        <script src="/libs/lightgallery/js/lg-video.min.js"></script>
    
    
        <script src="/libs/justified-gallery/jquery.justifiedGallery.min.js"></script>
    
    



<!-- Custom Scripts -->
<script src="/js/main.js"></script>

    </div>
</body>
</html>